package com.jgraves.WikiToSpeech;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.util.List;

import org.htmlcleaner.CleanerProperties;
import org.htmlcleaner.ContentNode;
import org.htmlcleaner.HtmlCleaner;
import org.htmlcleaner.HtmlNode;
import org.htmlcleaner.TagNode;
import org.htmlcleaner.TagNodeVisitor;

import android.content.Context;

/** Extracts script from web page (scriptTag = pre) or .txt file (scriptTag = body)
 * @author johngraves
 *
 */
public class ReadURL {

	public static void readURL(final Context context, InputStream instream, final Integer scriptSourceType) {
		if(null==instream){
			return;
		}

		HtmlCleaner cleaner = new HtmlCleaner();
		CleanerProperties props = cleaner.getProperties();
		props.setRecognizeUnicodeChars(true);

		TagNode node;

		try {
			//			node = cleaner.clean(new URL(siteUrl));
			node = cleaner.clean(instream);
			if ((scriptSourceType==Constants.TXT)||(scriptSourceType==Constants.ZIP)) {
				
				node.traverse(new TagNodeVisitor() {
					public boolean visit(TagNode tagNode, HtmlNode htmlNode) {
						if (htmlNode instanceof TagNode) {
							TagNode tag = (TagNode) htmlNode;
							String tagName = tag.getName();
							if ("body".equals(tagName)) {
								List<?> tagChildren = tag.getChildren();
								ContentNode tagChildrenContentNode = (ContentNode) tagChildren.get(0);
								StringBuilder tagChildrenContentNodeContents = tagChildrenContentNode.getContent();
								String[] preStringArray = tagChildrenContentNodeContents.toString().split("\n");
								State.setSequence(MakeSequence.makeSequence(context, preStringArray, (scriptSourceType==Constants.ZIP)));
							} 
						}
						// tells visitor to continue traversing the DOM tree
						return true;
					}
				});
				
			} else if (scriptSourceType==Constants.HTML) {

				node.traverse(new TagNodeVisitor() {
					public boolean visit(TagNode tagNode, HtmlNode htmlNode) {
						if (htmlNode instanceof TagNode) {
							TagNode tag = (TagNode) htmlNode;
							String tagName = tag.getName();
							// Try to find text marked <pre> </pre>
							if ("pre".equals(tagName)) { 
								StringBuffer tagChildrenContentNodeContents = tag.getText();
								String[] preStringArray = tagChildrenContentNodeContents.toString().split("\n");
								State.setSequence(MakeSequence.makeSequence(context, preStringArray, false));
								State.clearQuestionsVisited();
								State.setOnQuestion(0);
							} 
						}
						// tells visitor to continue traversing the DOM tree
						return true;
					}
				});
			}
			//			print("Sequence length:" + sequence.size());
		} catch (MalformedURLException e1) {
			e1.printStackTrace();
			//			speak("Sorry. Could not read the script.");
		} catch (IOException e1) {
			e1.printStackTrace();
			//			speak("Sorry. Could not read the script.");
		}
	}
}
